package org.qpcr.community.project.service;

import lombok.extern.slf4j.Slf4j;
import org.hswebframework.ezorm.rdb.mapping.ReactiveQuery;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
import org.qpcr.community.project.model.entity.TestItemInstanceEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.Map;

@Service
@Slf4j
public class LocalTestItemInstanceService extends GenericReactiveCrudService<TestItemInstanceEntity, String> {
    @Autowired
    private ReactiveRepository<TestItemInstanceEntity, String> repository;

    public Mono<TestItemInstanceEntity> findByItemName(String itemname) {
        return Mono.justOrEmpty(itemname).flatMap((_name) -> {
            return ((ReactiveQuery)this.repository.createQuery().where(TestItemInstanceEntity::getItem, _name)).fetchOne();
        });
    }

    public Mono<TestItemInstanceEntity> findByItemName(String itemname,String id) {
        return Mono.justOrEmpty(itemname).flatMap((_name) -> {
            return ((ReactiveQuery)this.repository.createQuery().where(TestItemInstanceEntity::getItem, _name).not(TestItemInstanceEntity::getId,id)).fetchOne();
        });
    }

    public Mono<TestItemInstanceEntity> findByItemCode(String itemcode,String id) {
        return Mono.justOrEmpty(itemcode).flatMap((_name) -> {
            return ((ReactiveQuery)this.repository.createQuery().where(TestItemInstanceEntity::getCode, _name).not(TestItemInstanceEntity::getId,id)).fetchOne();
        });
    }
    public Mono<TestItemInstanceEntity> findByItemCode(String itemcode) {
        return Mono.justOrEmpty(itemcode).flatMap((_name) -> {
            return ((ReactiveQuery)this.repository.createQuery().where(TestItemInstanceEntity::getCode, _name)).fetchOne();
        });
    }


    public Mono<Map<String,String>> findChannelMapByIds(Collection<String> ids){
        if (null == ids || ids.isEmpty()) {
            return Mono.empty();
        }
        return this.createQuery()
                .select(TestItemInstanceEntity::getId,TestItemInstanceEntity::getChannel)
                .in(TestItemInstanceEntity::getId,ids)
                .fetch()
                .collectMap(TestItemInstanceEntity::getId,TestItemInstanceEntity::getChannel);
    }
}
